import NodeRSA from 'node-rsa';
import * as fs from 'fs';
import * as path from 'path';

export class CryptoUtil {
  private static instance: CryptoUtil;
  private privateKey: NodeRSA;
  private publicKey: string;

  private constructor() {
    try {
      // 生成 RSA 密钥对
      const key = new NodeRSA({b: 1024});
      
      // 设置密钥格式，确保与前端 JSEncrypt 兼容
      key.setOptions({
        encryptionScheme: 'pkcs1', // 使用 PKCS#1 v1.5 填充方案
        environment: 'browser',     // 使用浏览器环境
        signingScheme: 'pkcs1-sha256' // 签名方案
      });
      
      this.privateKey = key;
      this.publicKey = key.exportKey('public');
      
      // 保存密钥对
      const keyPath = path.join(process.cwd(), 'config/rsa');
      if (!fs.existsSync(keyPath)) {
        fs.mkdirSync(keyPath, { recursive: true });
      }
      fs.writeFileSync(path.join(keyPath, 'private.key'), key.exportKey('private'));
      fs.writeFileSync(path.join(keyPath, 'public.key'), this.publicKey);
    } catch (error) {
      console.error('RSA密钥生成失败:', error);
      throw error;
    }
  }

  public static getInstance(): CryptoUtil {
    if (!CryptoUtil.instance) {
      CryptoUtil.instance = new CryptoUtil();
    }
    return CryptoUtil.instance;
  }

  // 获取公钥
  public getPublicKey(): string {
    return this.publicKey;
  }

  // 解密数据
  public decrypt(encryptedData: string): string {
    try {
      // 确保输入是 base64 格式
      const buffer = Buffer.from(encryptedData, 'base64');
      return this.privateKey.decrypt(buffer, 'utf8');
    } catch (error) {
      console.error('解密失败:', error);
      throw new Error('解密失败：' + error.message);
    }
  }
} 